﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using System.Collections.Generic;
using MvcContribJquery.Models;
using MvcContrib.Pagination;

namespace MvcContribJquery.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {

        private int pageSize = 6;
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult Sort(string ColumnName, int? PageNum, string GridDiv, string Controller, string Direction, string GridView)
        {
            // page number is pretty much never null
            // but with the coalescing operation, why be lazy?
            int page = PageNum ?? 1;
            // let's have a default sort order. we're hard coded to our Model, so
            // it's not a concern if we hard code the default sort order.
            string defaultColumn = "FirstName";
            string column = (ColumnName ?? defaultColumn) == "undefined" ? defaultColumn : 
                (ColumnName == String.Empty) ? defaultColumn : ColumnName;
            // default sort direction.
            string direction = (Direction ?? "ASC") == "undefined" ? "ASC" : Direction;
            // Linq to SQL data context
            DataLayerDataContext dc = new DataLayerDataContext();
            // AsPagination == from the MvcContrib.Pagination namespace.
            // also taking advantage of the dynamic query library for AJAX
            var peeps = dc.AwesomePeoples.OrderBy(column + " " + direction).AsPagination(page, pageSize);
            ViewData["peeps"] = peeps;
            ViewData["controller"] = Controller;
            ViewData["griddiv"] = GridDiv;
            return View(GridView);
        }
    }
}
